package com.fh.alipay.controller;

import com.alipay.api.AlipayApiException;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.fh.alipay.AliPayApiConfig;
import com.fh.alipay.AliPayApiConfigKit;
import com.fh.alipay.entity.AliPayBean;
import com.fh.alipay.po.User;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @FileName: BaseController
 * @Author: fh
 * @Date: 2021/12/17 15:14
 * @Description: JWT框架生成token
 * @Version: 1.0
 */
public class BaseController extends AbstractAliPayApiController {

    @Resource
    private AliPayBean aliPayBean;

    protected String getToken(User user) {
        String token="";
        token= JWT.create()
                .withKeyId(user.getUsername())
                .withIssuer("www.ikertimes.com")
                .withIssuedAt(new Date())
                .withJWTId("jwt.ikertimes.com")
                .withClaim("loginName", user.getUsername())
                .withAudience(user.getUsername())
                .sign(Algorithm.HMAC256(user.getPassword()));
        return token;
    }

    @Override
    public AliPayApiConfig getApiConfig() throws AlipayApiException {
        AliPayApiConfig aliPayApiConfig;
        try {
            aliPayApiConfig = AliPayApiConfigKit.getApiConfig(aliPayBean.getAppId());
        } catch (Exception e) {
            aliPayApiConfig = AliPayApiConfig.builder()
                    .setAppId(aliPayBean.getAppId())
                    .setAliPayPublicKey(aliPayBean.getPublicKey())
                    .setAppCertPath(aliPayBean.getAppCertPath())
                    .setAliPayCertPath(aliPayBean.getAliPayCertPath())
                    .setAliPayRootCertPath(aliPayBean.getAliPayRootCertPath())
                    .setCharset("UTF-8")
                    .setPrivateKey(aliPayBean.getPrivateKey())
                    .setServiceUrl(aliPayBean.getServerUrl())
                    .setSignType("RSA2")
                    // 普通公钥方式
                    .build();
            // 证书模式
//                    .buildByCert();

        }
        return aliPayApiConfig;
    }
}
